﻿using Furion;
using Microsoft.Extensions.Logging;
using Serilog.Core;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TulingMember.Core
{
    public class RedisHelper
    {

        private readonly ILogger _logger;
        private static string ConnectionString = App.GetConfig<string>("ConnectionStrings:RedisConnectionString");
        /// <summary>
        /// 静态变量锁
        /// </summary>
        private static object _locker = new Object();

        /// <summary>
        /// 静态实例
        /// </summary>
        private static ConnectionMultiplexer _instance = null;

        public RedisHelper( )
        {
            _logger = new LoggerFactory().CreateLogger("RedisLogger");
        }
        /// <summary>
        /// 使用一个静态属性来返回已连接的实例，如下列中所示。这样，一旦 ConnectionMultiplexer 断开连接，便可以初始化新的连接实例。
        /// </summary>
        private static ConnectionMultiplexer Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_locker)
                    {
                        if (_instance == null || !_instance.IsConnected)
                        {
                            _instance = ConnectionMultiplexer.Connect(ConnectionString); 
                        }
                    }
                }
                return _instance;
            }
        }

        /// <summary>
        /// 获取redis数据库对象
        /// </summary>
        /// <returns></returns>
        private static IDatabase GetDatabase()
        {
            return Instance.GetDatabase();
        }

        /// <summary>
        /// 检查Key是否存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool Exists(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return false;
            }
            return GetDatabase().KeyExists(key); 
        }

        /// <summary>
        /// 设置String类型的缓存对象(如果value是null或者空字符串则设置失败)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="ts">过期时间</param>
        public static bool SetString(string key, string value, TimeSpan? ts = null)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return false;
            }
            return GetDatabase().StringSet(key, value, ts); 
        }

        /// <summary>
        /// 根据key获取String类型的缓存对象
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetString(string key)
        {
            return GetDatabase().StringGet(key);
        }

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="key">key</param>
        /// <returns></returns>
        public static bool KeyDelete(string key)
        {
            return GetDatabase().KeyDelete(key);
        }
        /// <summary>
        /// 设置Hash类型缓存对象(如果value没有公共属性则不设置缓存)
        ///    会使用反射将object对象所有公共属性作为Hash列存储
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetHash(string key, object value)
        {
            if (null == value)
            {
                return;
            }
            List<HashEntry> list = new List<HashEntry>();
            Type type = value.GetType();
            var propertyArray = type.GetProperties();
            foreach (var property in propertyArray)
            {
                string propertyName = property.Name;
                string propertyValue = property.GetValue(value).ToString();
                list.Add(new HashEntry(propertyName, propertyValue));
            }
            if (list.Count < 1)
            {
                return;
            }
            IDatabase db = GetDatabase();
            db.HashSet(key, list.ToArray());
        }

        /// <summary>
        /// 设置Hash类型缓存对象(用于存储对象)
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="value">字典,key是列名 value是列的值</param>
        public static void SetHash(string key, Dictionary<string, string> value)
        {
            if (null == value || value.Count < 1)
            {
                return;
            }
            HashEntry[] array = (from item in value select new HashEntry(item.Key, item.Value)).ToArray();
            IDatabase db = GetDatabase();
            db.HashSet(key, array);
        }

        /// <summary>
        /// 根据key和列数组从缓存中拿取数据(如果fieldList为空或者个数小于0返回null)
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <param name="fieldList">列数组</param>
        /// <returns>根据列数组构造一个字典,字典中的列与入参列数组相同,字典中的值是每一列的值</returns>
        public static Dictionary<string, string> GetHash(string key, List<string> fieldList)
        {
            if (null == fieldList || fieldList.Count < 1)
            {
                return null;
            }
            Dictionary<string, string> dic = new Dictionary<string, string>();
            RedisValue[] array = (from item in fieldList select (RedisValue)item).ToArray();
            IDatabase db = GetDatabase();
            RedisValue[] redisValueArray = db.HashGet(key, array);
            for (int i = 0; i < redisValueArray.Length; i++)
            {
                string field = fieldList[i];
                string value = redisValueArray[i];
                dic.Add(field, value);
            }
            return dic;
        }

        /// <summary>
        /// 使用Redis 计数器
        /// </summary>
        /// <param name="key"></param>
        public static long StringIncrement(string key)
        {
            long index= GetDatabase().StringIncrement(key);

            if (index <= 1)
            {
                GetDatabase().KeyExpire(key, new TimeSpan(72, 0, 0));
            }
            return index;
        }
         
    }
}
